<?php

class MultiLevelCategory extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{multi_level_categories}}':
     * @var integer $id
     * @var string $name
     * @var integer $parent_id
     * @var string $icon_saved_path
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{multi_level_categories}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('name, parent_id, pinyin', 'required'),
            array('parent_id, order_pos, created, updated, level', 'numerical', 'integerOnly' => true),
            array('name, icon_saved_path', 'length', 'max' => 200),
            array('pinyin', 'length', 'max' => 1),
            array('sign', 'length', 'max' => 20),
            array('sign', 'unique'),
            array('sign', 'required', 'on' => 'checkIsRoot'),
            array('icon_saved_path', 'file',
                'allowEmpty' => true,
                'types' => 'jpg, jpeg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
//            // 主品牌产品
//            'mainBrandProducts' => array(self::HAS_MANY, 'Product', 'main_brand_id'),
//            // 次品牌产品
//            'subBrandProducts' => array(self::HAS_MANY, 'Product', 'sub_brand_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'name' => Yii::t('multiLevelCategory', 'name'),
            'parent_id' => Yii::t('multiLevelCategory', 'parent_id'),
            'sign' => Yii::t('multiLevelCategory', 'sign'),
            'icon_saved_path' => Yii::t('multiLevelCategory', 'icon_saved_path'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    const SIGN_NONE = '';
    const SIGN_BRAND = 'brand';

    public function getSignOptions() {
        return array(
            self::SIGN_NONE => Yii::t('multiLevelCategory', 'sign_none'),
            self::SIGN_BRAND => Yii::t('multiLevelCategory', 'sign_brand'),
        );
    }

    // 排序选项
    public function getOrderPosOptions() {
        $order = array();
        for ($i = 1; $i <= 60; $i++) {
            $order[$i] = "⇑　" . sprintf("%02d", $i) . '　↵';
        }
        return $order;
    }

    // 获取指定 id 下的所有品牌
    private $_ids;
    public function getIds($parent_id = 1, $include_self = true, $include_subs = true) {
        if ($include_self) $this->_ids[] = $parent_id;
        $criteria = new CDbCriteria();
        $criteria->condition = "parent_id = {$parent_id}";
        $criteria->select = array('id');
        $nodes = self::model()->findAll($criteria);
        foreach ($nodes as $node) {
            $node_id = $node->id;
            if ($include_subs) {
                if (self::hasChild($node_id)) {
                    $this->_ids[] = $node_id;
                    $this->getIds($node_id);
                } else {
                    $this->_ids[] = $node_id;
                }
            } else {
                $this->_ids[] = $node_id;
            }
        }
        return array_unique($this->_ids);
    }

    /**
     * 返回 CTreeView 所需数据
     * @param <integer> $parent_id
     * @return <string>
     */
    public function getCTreeViewDatas($parent_id = 1, $url = 'MultiLevelCategory/index') {
        $datas = $this->generateCTreeViewDatas($parent_id, $url);
        if (count($datas)) {
            return YArrayExt::toTree($datas, 'id', 'parent', 'children', $refs);
        } else {
            return $datas;
        }
    }

    // 遍历节点属于 $parent_id 的所有子节点，供 getCTreeViewDatas 生成返回 CTreeView 所需数据
    private $_CTreeView_datas;
    public function generateCTreeViewDatas($parent_id = 1, $url = 'MultiLevelCategories/index') {
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$parent_id}";
        $criteria->order = 'order_pos ASC';
        $brands = self::model()->findAll($criteria);
        foreach ($brands as $j => $brand) {
            $brand_id = $brand->id;
            if (self::hasChild($brand_id)) {
                $this->_CTreeView_datas[$brand_id] = array(
                    'id' => $brand_id,
                    'text' => CHtml::link($brand->name, array($url, 'id' => $brand->id)),
//                    'text' => "<span>{$node->name}</span>",
                    'expanded' => true,
                    'classes' => 'important',
                    'parent' => $brand->parent_id,
                    'order_pos' => $brand->order_pos,
                );
                $this->generateCTreeViewDatas($brand_id, $url);
            } else {
                $this->_CTreeView_datas[$brand_id] = array(
                    'id' => $brand_id,
                    'text' => CHtml::link($brand->name, array($url, 'id' => $brand->id)),
                    'expanded' => false,
                    'classes' => 'important',
                    'parent' => $brand->parent_id,
                    'order_pos' => $brand->order_pos,
                );
            }
        }

        return $this->_CTreeView_datas;
    }

    /**
     * 判断是否有子节点
     * @param integer $node_id
     * @return boolean
     */
    public static function hasChild($node_id) {
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$node_id}";
        return (self::model()->count($criteria)) ? true : false;
    }

    // 格式化更新时间
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '-';
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }


    private $_original_icon_saved_path;
    public function afterFind() {
        $this->_original_icon_saved_path = $this->icon_saved_path;
    }

    public function beforeValidate() {
//        if ($this->isNewRecord) {
//                $this->setScenario('is_picture_link');
//            } else {
//                if ($this->_original_logo_filename == '') {
//                    $this->setScenario('is_picture_link');
//                }
//            }
        if ($this->parent_id == 1) {
            $this->level = 0;
            $this->setScenario('checkIsRoot');
        } else {
            $this->level = self::model()->findByPk($this->parent_id)->level + 1;
        }
        Yii::import('application.extensions.Hanzi.HanziTools');
        $pzt = new HanziTools();
        $pinyin = strtoupper(substr($pzt->getShortPinyin($this->name), 0, 1));
        $this->pinyin = (empty($pinyin) ? '#' : $pinyin);
        $uploading_file = CUploadedFile::getInstance($this, 'icon_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
//            echo 'heee';exit;
            if (!$this->isNewRecord) {
                $model = self::model()->findByPk($this->id);
                @unlink($model->icon_saved_path);
            }
            $filename = md5(time()) . '.' . $uploading_file->getExtensionName();
            $this->icon_saved_path = $filename;
            $this->_original_icon_saved_path = $filename;
            $uploading_file->saveAs(Yii::getPathOfAlias('webroot') . '/upload/multiLevelCategories/' . $filename);
        } else {
            $this->icon_saved_path = $this->_original_icon_saved_path;
        }

//        echo $this->file_saved_path;
        return true;
    }

    public function afterValidate() {
        if ($this->hasErrors()) {
            @unlink(Yii::app()->basePath . '/../upload/multiLevelCategories/' . $this->_original_icon_saved_path);
        }
    }

    public function afterDelete() {
        @unlink($this->iconPath);
    }

    // get ICON saved path
    public function getIconPath() {
        return dirname(Yii::app()->basePath) . '/upload/multiLevelCategories/' . $this->icon_saved_path;
    }

    /**
     * get pic file source
     * @return string
     */
    public function getIconSource() {
        $icon_saved_path = trim($this->icon_saved_path);
        return ($icon_saved_path != '')
            ? Yii::app()->request->baseUrl . '/upload/multiLevelCategories/' . $icon_saved_path
            : '';
    }

    /**
     * get image html element
     * @return string
     */
    public function getIconImageTag() {
        return ($this->iconSource != '')
            ? CHtml::image($this->iconSource, $this->name)
            : '';
    }

    /**
     * 获取当前品牌分类的级别
     * 注意：只区分０、1、2级，ROOT 为 0 级
     * @return integer
     */
//    public function getLevel() {
//        switch ($this->parent_id) {
//            case 0:
//                return 0; break;
//            case 1:
//                return 1; break;
//            default:
//                return 2;
//        }
//    }
}